package org.zxyj.manage.controller;

import java.awt.image.BufferedImage;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import javax.servlet.http.HttpSession;

import org.zxyj.manage.entity.CoursePaperDetail;
import org.zxyj.manage.entity.Examinee;
import org.zxyj.manage.service.ICheckService;
import org.zxyj.manage.service.ICoursePaperService;
import org.zxyj.manage.service.ICropService;
import org.zxyj.manage.service.IPointRecognitionService;
import org.zxyj.manage.thread.GetInstanceService;

/**
 * 答卷校验线程任务处理类
    * @ClassName: PaperCheckThread
    * @author liuyong
    * @date 2016年8月12日
 */
@SuppressWarnings("unchecked")
public class PaperCheckThread implements Runnable{
	public int i=-1;
    public String kmdjUrl = "";
    public String baseUrl = "";
    public List<CoursePaperDetail> list = null;
    public Map<String,CoursePaperDetail> kmdjListMap = null;
    public Map<String,Object> posMap1 = null;
    public Map<String,Object> posMap2 = null;
    public Map<String,Object> ksbhMap = null;
    public int areaWidth = 0;
    public int areaHeight = 0;
    public Map<String,Object> qkMap = null;
    public Map<String,Examinee> ksAllMap = null;
    public Map<String,Map<String,Object>> cjcsMap = null;
    public Map<String,String> ksxxMap = null;
    public static Object lock = new Object();
    public HttpSession session = null;
    
	private ICropService cropService = GetInstanceService.getInstance().getCropService();
	private ICheckService checkService = GetInstanceService.getInstance().getCheckService();
	private IPointRecognitionService pointRecognitionService = GetInstanceService.getInstance().getPointRecognitionService();
    private ICoursePaperService coursePaperService = GetInstanceService.getInstance().getCoursePaperService();
    
	public PaperCheckThread(Map<String,Object> map){
        i = Integer.valueOf(map.get("threadNum")+"");
        session = (HttpSession) map.get("session");
        list = (List<CoursePaperDetail>) map.get("rList");
        kmdjListMap = (Map<String, CoursePaperDetail>) map.get("kmdjListMap");
        posMap1 = (Map<String, Object>) map.get("posMap1");
        posMap2 = (Map<String, Object>) map.get("posMap2");
        ksbhMap = (Map<String, Object>) map.get("ksbhMap");
        qkMap = (Map<String, Object>) map.get("qkMap");
        ksAllMap = (Map<String, Examinee>) map.get("ksAllMap");
        areaWidth = Integer.valueOf(map.get("areaWidth")+"");
        areaHeight = Integer.valueOf(map.get("areaHeight")+"");
        cjcsMap = (Map<String, Map<String, Object>>) map.get("cjcsMap");
        ksxxMap = (Map<String, String>) map.get("ksxxMap");
        baseUrl = (String) map.get("baseUrl");
    }
    
	public void run(){
    	ConcurrentHashMap<String,String> map = new ConcurrentHashMap<String,String>();
        Map<String,Map<String,Integer>> kmdjDiffAll = new HashMap<String,Map<String,Integer>>();//存放答卷记录的偏差值信息
        Map<String, CoursePaperDetail> sbsbMap = new HashMap<String,CoursePaperDetail>();//无法识别map或识别结果不能完全识别
        Map<String,String> sbcgMap = new HashMap<String,String>();//识别成功map
        Map<String,String> kmdjQkMap = new HashMap<String,String>();//缺考map
        Map<String,String> bdsbMap = new HashMap<String,String>();//考生比对失败map
        Map<String,String> rotateMap = new HashMap<String, String>();//答卷偏正角度map
        int clzs=0;//校验总数
        
        ConcurrentHashMap<String, Object> map1 = (ConcurrentHashMap<String, Object>) session.getAttribute("kmdjJyjgMap");
        Map<String,Map<String,String>> sbcgMap1 = (Map<String, Map<String, String>>) session.getAttribute("sbcgMap");
        Map<String,Map<String,CoursePaperDetail>> sbsbMap1 = (Map<String, Map<String, CoursePaperDetail>>) session.getAttribute("sbsbMap");
        Map<String,Map<String,String>> kmdjQkMap1 = (Map<String, Map<String, String>>) session.getAttribute("kmdjQkMap");
        Map<String,Map<String,String>> bdsbMap1 = (Map<String, Map<String, String>>) session.getAttribute("bdsbMap");
        Map<String,Integer> qkksMap1 = (Map<String, Integer>) session.getAttribute("qkksMap");//缺考考生数
        
        try{
        	for(CoursePaperDetail record : list){
        		String recordId = record.getId();//答卷记录id
                String mbid1 = record.getCourseTemplateId();//正面模板id
                String file_name = record.getFileName();//文件名称-简称
                String fileName = record.getFilePath();//文件全称
                String kmdjUrl = baseUrl + fileName;//答卷存储路径
                BufferedImage tzdImage = cropService.cropPosBuffered(kmdjUrl,null);//裁剪特征点区域
                
                /****判断答卷正反面,后面需要继续优化调整 TODO***/
                //第一遍获取答卷起始定位点
                Map<String, Integer> posDiffMap1 = checkService.getTempStartPointFirst(tzdImage);
                int start_pos_x = posDiffMap1.get("start_pos_x");//实际答卷定位点X
                int start_pos_y = posDiffMap1.get("start_pos_y");//实际答卷定位点Y
                
                /**************对答卷进行偏正校正 start******************/
                Map<String,Object> args = new HashMap<String,Object>();
                args.put("sourceUrl", kmdjUrl);
                args.put("start_pos_x", start_pos_x);
                args.put("start_pos_y", start_pos_y);
                Map<String,Object> jzResultMap = checkService.getBufferedResultForCheck(args);
                String rotate = jzResultMap.get("rotate")+"";//偏正角度
                BufferedImage image = (BufferedImage)jzResultMap.get("image");//校正后图像流
                rotateMap.put(recordId, rotate);
                /**************对答卷进行偏正校正 end******************/
                
                //第二遍获取答卷起始定位点
                tzdImage = cropService.cropPosBuffered(image,null);//裁剪特征点区域
                args.clear();
                args.put("image", tzdImage);
                args.put("record", posMap1.get(mbid1));
                //获取模板起始坐标点与答卷起始点偏差值
                //posDiffMap = checkService.getTempStartPoint(tzdImage,(Map<String,Object>)posMap1.get(mbid1));
                Map<String, Integer> posDiffMap = checkService.getTempStartPoint(args);
                tzdImage = null;
                int p_x = posDiffMap.get("p_x");
                int p_y = posDiffMap.get("p_y");
                
                //获取考生编号区域图片流
                args.clear();
                args.put("image", image);
                args.put("p_x", p_x);
                args.put("p_y", p_y);
                args.put("ksMap", ksbhMap.get(mbid1));
                Map<String,Object> ksbhAreaMap = checkService.getKsbhBufferedImage(args);
                //Map<String,Object> ksbhAreaMap = checkService.getKsbhBufferedImage((Map<String,Object>)ksbhMap.get(mbid1),image,p_x,p_y);
                BufferedImage khImage = (BufferedImage)ksbhAreaMap.get("khImage");//读取考生编号文件流
                int area_width = Integer.parseInt(ksbhAreaMap.get("area_width")+"");
                int area_height = Integer.parseInt(ksbhAreaMap.get("area_height")+"");
                int kh_start_x = Integer.parseInt(ksbhAreaMap.get("kh_start_x")+"");
                int kh_start_y = Integer.parseInt(ksbhAreaMap.get("kh_start_y")+"");
                int singleWidth = areaWidth;
                int singleHeight = areaHeight;
                int row_count = Integer.parseInt(ksbhAreaMap.get("row_count")+"");
                int col_count = Integer.parseInt(ksbhAreaMap.get("col_count")+"");
                
                //正面答卷比对偏差值map
                Map<String,Integer> diffMap = new HashMap<String,Integer>();
                diffMap.put("p_x", p_x);
                diffMap.put("p_y", p_y);
                String studentNo ="";
                //识别考生编号区域内考号信息
                args.clear();
                args.put("image", khImage);
                args.put("width", area_width);
                args.put("height", area_height);
                args.put("start_x", kh_start_x);
                args.put("start_y", kh_start_y);
                args.put("singleWidth", singleWidth);
                args.put("singleHeight", singleHeight);
                args.put("row_count", row_count);
                args.put("col_count", col_count);
                Map<String, String> resultMap = pointRecognitionService.recognitionKsbh(args);
                //Map<String, String> resultMap = pointRecognitionService.recognitionKsbh(khImage,area_width,area_height,kh_start_x,kh_start_y,singleWidth,singleHeight,row_count,col_count);
                khImage = null;
                String flag = resultMap.get("flag");
                
                args.clear();
                args.put("record", qkMap.get(mbid1));
                args.put("image", image);
                args.put("p_x", p_x);
                args.put("p_y", p_y);
                boolean qkFlag = checkService.judgeQk(args);
                if(flag.equals("0")){
                    sbsbMap.put(recordId, record);//考生编号识别失败,将该记录id存放入无法识别map中
                    kmdjDiffAll.put(recordId, diffMap);
                    /*******继续判断是否缺考答卷**********/
                    //boolean qkFlag = checkService.judgeQk((Map<String,Object>)qkMap.get(mbid1),image,p_x,p_y);
                    if(qkFlag){
                        //缺考，则不需要进行后续处理
                        if(!kmdjListMap.isEmpty()){//存在反面模板
                        	CoursePaperDetail r = kmdjListMap.get(file_name.split("_")[0]);
                            String recordId3 = r.getId();//反面答卷记录id
                            kmdjQkMap.put(recordId3, studentNo);//记录反面缺考的考号答卷记录
                        }
                        kmdjQkMap.put(recordId, studentNo);//记录正面缺考的考号答卷记录
                    }else{
                        //不缺考时，则继续校验反面是否符合要求
                        if(!kmdjListMap.isEmpty()){//存在反面模板
                        	CoursePaperDetail r = kmdjListMap.get(file_name.split("_")[0]);
                        	if(r!=null){
	                            String recordId2 = r.getId();//反面答卷记录id
	                            Map<String, Integer> diffMap2 = new HashMap<String,Integer>();
	                            diffMap2 = checkService.cropCheckFmdj(r,posMap2);
	                            //存放识别失败反面答卷
	                            sbsbMap.put(recordId2, r);//将识别失败的考号记录
	                            kmdjDiffAll.put(recordId2, diffMap2);
                        	}
                        }
                    }
                }else{
                	studentNo = resultMap.get("result");//获取解析出的考号
                    //比对该考号是否存在于考生集合中,如不存在则说明识别有误，否则正确
                    if(ksAllMap.get(studentNo)!=null){
                        sbcgMap.put(recordId, studentNo);//将识别成功的考号记录
                        kmdjDiffAll.put(recordId, diffMap);
                        
                        /*******继续判断是否缺考答卷**********/
                        /*try {
                            qkFlag = checkService.judgeQk((Map<String,Object>)qkMap.get(mbid1),image,p_x,p_y);
                        } catch (IOException e1) {
                            e1.printStackTrace();
                        }*/
                        if(qkFlag){
                            //缺考，则不需要进行后续处理
                            if(!kmdjListMap.isEmpty()){//存在反面模板
                            	CoursePaperDetail r = kmdjListMap.get(file_name.split("_")[0]);
                                String recordId3 = r.getId();//反面答卷记录id
                                kmdjQkMap.put(recordId3, studentNo);//记录反面缺考的考号答卷记录
                            }
                            kmdjQkMap.put(recordId, studentNo);//记录正面缺考的考号答卷记录
                        }else{
                            //不缺考且考号存在时，则继续校验反面是否符合要求
                        	Map<String,Object> param = new HashMap<String,Object>();
                        	param.put("record",record);
                        	param.put("image", image);
                        	param.put("kmdjDiffAll",kmdjDiffAll);
                        	param.put("cjcsMap",cjcsMap);
                        	param.put("ksxxMap",ksxxMap);
                        	param.put("studentNo",studentNo);
                            cropService.cropImageForZm(param);//裁剪图片-正面
                        	//cropService.cropImageForZm(session,record,image,kmdjDiffAll,cjcsMap,studentNo,ksxxMap);//裁剪图片-正面
                            image=null;
                            if(!kmdjListMap.isEmpty()){//存在反面模板
                            	CoursePaperDetail r = kmdjListMap.get(file_name.split("_")[0]);
                                String recordId2 = r.getId();//反面答卷记录id
                                Map<String, Integer> diffMap2 = new HashMap<String, Integer>();
                                diffMap2 = checkService.cropCheckFmdj(r,posMap2);
                                //裁剪校验反面答卷
                                sbcgMap.put(recordId2, studentNo);//将识别成功的考号记录
                                kmdjDiffAll.put(recordId2, diffMap2);
                                param.put("record",r);
                                param.put("image", image);
                            	param.put("kmdjDiffAll",kmdjDiffAll);
                            	cropService.cropImageForFm(param);
                                //cropService.cropImageForFm(session,r,kmdjDiffAll,cjcsMap,studentNo,ksxxMap);//裁剪图片-反面
                            }
                        }
                    }else{
                        bdsbMap.put(studentNo, studentNo);
                    }
               }
               System.out.println("___识别考生编号为："+studentNo);
               
               clzs++;//存放已处理数
               map1.put("clzs_"+i, clzs+"");
               session.setAttribute("kmdjJyjgMap",map1);
        	}
        	
        	int qkCount =0;//缺考记录数
            if(kmdjQkMap!=null){
                if(!kmdjListMap.isEmpty()){//存在反面模板记录数除2，得到考生数
                    qkCount = kmdjQkMap.size()/2;
                }else{
                    qkCount = kmdjQkMap.size();
                }
            }
            
            Integer qkCount1 = qkksMap1.get("qkCount_"+i);
            if(qkCount1 ==null){
                qkCount1 = qkCount;
            }else{
                qkCount1 = qkCount1 + qkCount;
            }
            qkksMap1.put("qkCount_"+i, qkCount);
            sbcgMap1.put("sbcgMap_"+i, sbcgMap);
            sbsbMap1.put("sbsbMap_"+i, sbsbMap);
            kmdjQkMap1.put("kmdjQkMap_"+i, kmdjQkMap);
            bdsbMap1.put("bdsbMap_"+i, bdsbMap);
            
            map = (ConcurrentHashMap<String, String>) session.getAttribute("kmdjJyjgMap");
            map.put("succCount_"+i, sbcgMap.size()+"");//成功记录数
            map.put("sbsbCount_"+i, sbsbMap.size()+"");//识别失败记录数
            map.put("bdsbCount_"+i, bdsbMap.size()+"");//比对失败记录数
            map.put("qkCount_"+i, qkCount1+"");//缺考记录数
            
            session.setAttribute("kmdjJyjgMap",map);
            session.setAttribute("sbcgMap",sbcgMap1);
            session.setAttribute("sbsbMap",sbsbMap1);
            session.setAttribute("bdsbMap",bdsbMap1);
            session.setAttribute("kmdjQkMap",kmdjQkMap1);
            session.setAttribute("qkksMap",qkksMap1);
        	
        	//更新答卷校验数据
            Map<String,Object> args = new HashMap<String,Object>();
            args.put("kmdjDiffAll", kmdjDiffAll);
            args.put("sbcgMap", sbcgMap);
            args.put("sbsbMap", sbsbMap);
            args.put("kmdjQkMap", kmdjQkMap);
            args.put("rotateMap", rotateMap);
            this.coursePaperService.updatePaperCheckResult(args);
            //this.ckeckController.updateKmdjCheckResult(session,kmdjDiffAll,sbcgMap,sbsbMap,kmdjQkMap,rotateMap);
            Thread.sleep(100);
        }catch(Exception e){
            e.printStackTrace();
            System.out.println("线程处理发生异常！");
        }
    }
}
